package com.mit.wx.listener;

import com.mit.wx.conf.AdminConfiguration;
import com.mit.wx.dto.AdminDto;
import com.mit.wx.entity.Admin;
import com.mit.wx.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * 2018/10/20 Create by 郭文梁
 * InitAdminListener
 * 监听服务启动并且初始化超级管理员用户
 *
 * @author 郭文梁
 * @date 2018/10/20
 */
@Component
@Slf4j
public class InitAdminListener implements ApplicationRunner {
    private final AdminService adminService;
    private final AdminConfiguration adminConfiguration;

    @Autowired
    public InitAdminListener(AdminService adminService, AdminConfiguration adminConfiguration) {
        this.adminService = adminService;
        this.adminConfiguration = adminConfiguration;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        String name = adminConfiguration.getName();
        String password = adminConfiguration.getPassword();

        AdminDto admin = adminService.findByName(name);
        if (admin == null) {
            //管理员用户不存在
            Admin target = new Admin();
            target.setName(name);
            target.setPassword(DigestUtils.md5Hex(password));
            Admin result = adminService.save(target);
            log.info("Admin user init (save) success, name={}, password={}", result.getName(), result.getPassword());
        } else {
            //已存在
            String encodedPwd = DigestUtils.md5Hex(password);
            if (admin.getPassword().equalsIgnoreCase(encodedPwd)) {
                //信息一致，无需再修改
                log.info("Administrator user already exists, name={}, password={}", admin.getName(), admin.getPassword());
            } else {
                //修改密码
                Admin target = new Admin();
                target.setName(name);
                target.setPassword(encodedPwd);
                target.setId(admin.getId());
                Admin result = adminService.update(target);
                log.info("Admin user init (update) success, name={}, password={}", result.getName(), result.getPassword());
            }
        }
    }
}
